package com.hd.trans.db;

import static com.translation.assistant.extension.LanguageExtKt.mapping;

import android.content.Context;
import android.util.Log;

import com.hd.trans.R;
import com.hd.trans.db.bean.FileTranslateRecord;
import com.hd.trans.db.bean.HuDunLanguage;
import com.hd.trans.db.bean.LanguageGroup;
import com.hd.trans.db.bean.LanguageRecord;
import com.hd.trans.db.bean.Limit4UseBean;
import com.hd.trans.db.bean.TranslateRecord;
import com.hd.trans.db.greenDao.DaoMaster;
import com.hd.trans.db.greenDao.DaoSession;
import com.hd.trans.db.greenDao.FileTranslateRecordDao;
import com.hd.trans.db.greenDao.HuDunLanguageDao;
import com.hd.trans.db.greenDao.LanguageRecordDao;
import com.hd.trans.db.greenDao.Limit4UseBeanDao;
import com.hd.trans.db.greenDao.TranslateRecordDao;
import com.hd.trans.framework.dialog.LanguageDialogType;
import com.hd.trans.homefun.EventCode;
import com.hd.trans.ui.base.AppContextProvider;
import com.hd.trans.utils.StringUtils;
import com.translation.assistant.data.OfflineConstant;

import org.greenrobot.greendao.database.Database;

import java.util.ArrayList;
import java.util.List;
import java.util.TreeMap;

public class DataBaseMgr {
    private final static String DB_NAME = "trans_language.db";
    private final static String DB_PWD = "trans_language_pwd";


    private static DataBaseMgr mInstance;


    private DaoSession daoSession;


    public static synchronized DataBaseMgr getInstance() {
        if (mInstance == null) {
            mInstance = new DataBaseMgr(AppContextProvider.getContext());
        }
        return mInstance;
    }

    public static void init(Context context) {
        mInstance = new DataBaseMgr(context);
    }


    public DataBaseMgr(Context context) {
        if (daoSession == null) {
           /* DaoMaster.DevOpenHelper helper = new DaoMaster.DevOpenHelper(context, DB_NAME);
            SQLiteDatabase db = helper.getWritableDatabase();*/
            // 2、创建数据库连接
            /** 数据库升级 */
            MyOpenHelper helper = new MyOpenHelper(context, DB_NAME);
            Database db = null;
            try {
                db = helper.getEncryptedWritableDb(DB_PWD);// helper.getWritableDb();
            }catch (Exception e){
                e.printStackTrace();
            }
            // Database db = helper.getWritableDb();// helper.getWritableDb();
            if(db != null)
                daoSession = new DaoMaster(db).newSession();
        }
    }

    public DaoSession getDaoSession() {
        return daoSession;
    }

    /**
     * 获取所有语言
     */
    public List<HuDunLanguage> getAllLanguages(boolean isIncludeAuto) {
//        return daoSession.getHuDunLanguageDao().queryBuilder().orderAsc(HuDunLanguageDao.Properties.Name).list();
        if(!isIncludeAuto){
            return daoSession.getHuDunLanguageDao().queryBuilder()
                    .where(HuDunLanguageDao.Properties.Name.notEq("自动检测"))
                    .list();
        }
        return daoSession.getHuDunLanguageDao().loadAll();
    }

    /**
     * 获取所有语言
     */
    public TreeMap<String, HuDunLanguage> getLanguages(boolean isVoice) {
        TreeMap<String, HuDunLanguage> map = null;
        List<HuDunLanguage> allLanguages;
        if (isVoice) {
            allLanguages = daoSession.getHuDunLanguageDao().queryBuilder()
                    .where(HuDunLanguageDao.Properties.SupportVoice.eq(1))
                    .orderAsc(HuDunLanguageDao.Properties.FirstLetter).list();
        } else {
            allLanguages = daoSession.getHuDunLanguageDao().queryBuilder()
                    .orderAsc(HuDunLanguageDao.Properties.FirstLetter).list();
        }
        if(allLanguages != null && allLanguages.size() > 0){
            map = new TreeMap<>();
            for(HuDunLanguage language:allLanguages){
                map.put(language.getName(),language);
            }
        }
        return map;
    }

    /**
     * 添加语言
     */
    public void addLanguages(List<HuDunLanguage> languages) {
        if (languages == null || languages.isEmpty())
            return;
        daoSession.getHuDunLanguageDao().insertInTx(languages);
    }

    public void deleteAllLanguages() {
        daoSession.getHuDunLanguageDao().deleteAll();
    }

    public void deleteLanguage(HuDunLanguage languages) {
        if (languages != null)
            daoSession.getHuDunLanguageDao().deleteInTx(languages);
    }

    public void deleteLanguage(List<HuDunLanguage> languages) {
        if (languages == null || languages.isEmpty())
            return;
        daoSession.getHuDunLanguageDao().deleteInTx(languages);
    }

    /**
     * 根据名称获取
     *
     * @param name
     * @return
     */
    public HuDunLanguage getLanguageByName(String name) {
        if (StringUtils.isEmpty(name))
            return null;
        if(name.equals("中文")){//向下兼容，1.1.5之后的版本“中文”名称为“中文（简体）”
            name = "zh";
        }
        HuDunLanguage result = daoSession.getHuDunLanguageDao().queryBuilder().where(HuDunLanguageDao.Properties.Name.eq(name)).unique();
        if(result == null){
            result = daoSession.getHuDunLanguageDao().queryBuilder().where(HuDunLanguageDao.Properties.TranslateCode.eq(name)).unique();
        }
        return result;
    }

    /**
     * 根据翻译code获取
     *
     * @param name
     * @return
     */
    public HuDunLanguage getLanguageByTransCode(String name) {
        if (StringUtils.isEmpty(name))
            return null;

        HuDunLanguage result = daoSession.getHuDunLanguageDao().queryBuilder().where(HuDunLanguageDao.Properties.TranslateCode.eq(name)).unique();
        if(result == null){
            result = daoSession.getHuDunLanguageDao().queryBuilder().where(HuDunLanguageDao.Properties.Name.eq(name)).unique();
        }
        return result;
    }


    /**
     * 添加记录
     */
    public long addTranslateRecord(TranslateRecord record) {
        if (record == null)
            return -1;
        return daoSession.getTranslateRecordDao().insertOrReplace(record);
    }

    /**
     * 更新记录
     */
    public void updateTranslateRecord(TranslateRecord record) {
        if (record == null)
            return;
        daoSession.getTranslateRecordDao().update(record);
    }

    /**
     * 添加图片翻译记录
     */
    public long addFileTranslateRecord(FileTranslateRecord record) {
        if (record == null)
            return -1;
        return daoSession.getFileTranslateRecordDao().insertOrReplace(record);
    }

    /**
     * 更新图片翻译记录
     */
    public void updateFileTranslateRecord(FileTranslateRecord record) {
        if (record == null)
            return;
        daoSession.getFileTranslateRecordDao().update(record);
    }

    /**
     * 根据id获取图片翻译记录
     */
    public FileTranslateRecord getFileTranslateRecordByTime(long time) {
        if (time < 0)
            return null;
        return daoSession.getFileTranslateRecordDao().queryBuilder().where(FileTranslateRecordDao.Properties.CreateTime.eq(time)).unique();
    }

    /**
     * 获取图片翻译记录
     */
    public List<FileTranslateRecord> getFileTranslateRecord() {
        return daoSession.getFileTranslateRecordDao().loadAll();
    }

    public void deleteFileTranslateRecord(FileTranslateRecord record) {
        if (record != null)
            daoSession.getFileTranslateRecordDao().delete(record);
    }

    /**
     * 删除记录
     */
    public void deleteRecords(List<TranslateRecord> records) {
        if (records != null && !records.isEmpty())
            daoSession.getTranslateRecordDao().deleteInTx(records);
    }

    public void deleteRecord(TranslateRecord record) {
        if (record != null)
            daoSession.getTranslateRecordDao().delete(record);
    }

    /**
     * 删除全部记录
     */
    public void deleteAllRecord() {
        daoSession.getTranslateRecordDao().deleteAll();
    }

    /**
     * 删除收藏记录
     */
    public void deleteCollectRecords(List<TranslateRecord> records) {
        for (TranslateRecord record : records) {
            record.setIsCollected(false);
        }
        daoSession.getTranslateRecordDao().updateInTx(records);
    }

    /***************************************************  LanguageRecord ***************************************************************/

    private static final int MAX_NUM_LANGUAGE_RECORD = 15;//只记录最新的15条

    /**
     * 添加语言使用记录
     */
    public void addLanguageRecord(HuDunLanguage language, boolean isVoice) {
        if (language == null)
            return;

        LanguageRecord record = new LanguageRecord();
        record.setIsVoice(isVoice);
        record.setLanguage(language);
        record.setTriggerTime(System.currentTimeMillis());
        addLanguageRecord(record);
    }


    /**
     * 添加语言使用记录
     */
    public void addLanguageRecord(LanguageRecord record) {
        if (record == null)
            return;
        daoSession.getLanguageRecordDao().insertOrReplace(record);
    }

    /**
     * 获取识别语言
     *
     * @return
     */
    public List<HuDunLanguage> getDistinguishLanguages() {
        List<HuDunLanguage> languages = daoSession.getHuDunLanguageDao().queryBuilder()
                .where(HuDunLanguageDao.Properties.SupportDiscern.eq(1))
                .orderAsc(HuDunLanguageDao.Properties.FirstLetter)
                .list();
        return languages;
    }

    /**
     * 获取常用语言
     *
     * @return
     */
    public List<HuDunLanguage> getCommonRecordLanguages(boolean isVoice) {

        deleteExtraRecord(isVoice);
        List<HuDunLanguage> languages = new ArrayList<>();
        List<LanguageRecord> records = daoSession.getLanguageRecordDao().queryBuilder()
                .where(LanguageRecordDao.Properties.IsVoice.eq(isVoice))
                .orderDesc(LanguageRecordDao.Properties.Id)
                .list();
        for (LanguageRecord record : records) {
            languages.add(record.getLanguage());
        }
        return languages;
    }


    /**
     * 获取常用语言
     *
     * @return
     */
    public List<HuDunLanguage> getCommonRecordLanguages(
            boolean isNation,
            boolean isVoice,
            boolean isFrom,
            HuDunLanguage fromLang,
            HuDunLanguage toLang) {

        return getCommonRecordLanguages(isNation, isVoice, isFrom, fromLang, toLang, null);
    }

    /**
     * 获取常用语言
     *
     * @return
     */
    public List<HuDunLanguage> getCommonRecordLanguages(
            boolean isNation,
            boolean isVoice,
            boolean isFrom,
            HuDunLanguage fromLang,
            HuDunLanguage toLang,
            List<String> filterLangList) {

        deleteExtraRecord(isVoice);
        List<HuDunLanguage> languages = new ArrayList<>();
        if(isFrom && !isVoice){
            HuDunLanguage auto = DataBaseMgr.getInstance().getLanguageByName("自动检测");
            languages.add(0, auto);
        }

        if(isFrom){
            if(null != fromLang && !"自动检测".equals(fromLang.getName())){
                languages.add(fromLang);
            }
        }else {
            if(null != toLang && !"自动检测".equals(toLang.getName())){
                languages.add(toLang);
            }
        }


        List<LanguageRecord> records = daoSession.getLanguageRecordDao().queryBuilder()
                .where(LanguageRecordDao.Properties.IsVoice.eq(isVoice))
                .orderDesc(LanguageRecordDao.Properties.Id)
                .list();
        for (LanguageRecord record : records) {
            if(record.getLanguage() == null){
                continue;
            }
            if (null != fromLang) {
                if (record.getLanguage().getName().equals(fromLang.getName())) continue;
            }
            if (null != toLang) {
                if (record.getLanguage().getName().equals(toLang.getName())) continue;
            }
            String languageName = record.getLanguage().getName();
            if(isNation){
                if (!languageName.equals("中文（简体）")
                        && !languageName.equals("维吾尔语")
                        && !languageName.equals("藏语")
                        && !languageName.equals("蒙古语")
                ) {
                    continue;
                }
            }

            //过滤不支持的语种
            if(filterLangList != null && filterLangList.size() > 0){
                if(filterLangList.contains(languageName)){
                    continue;
                }
            }

            if(isFrom && !isVoice){
                if(languages.size() >= 4){
                    break;
                }
            }else if(languages.size() >= 3){
                break;
            }

            languages.add(record.getLanguage());
        }

        return languages;
    }

    public List<HuDunLanguage> getCommonRecordLanguages(
            LanguageDialogType type,
            boolean isFrom,
            boolean isOfflineLang
    ) {

        deleteExtraRecord();
        List<HuDunLanguage> languages = new ArrayList<>();
        List<String> addLanguages = new ArrayList<>();
        if(isFrom && !isOfflineLang && type == LanguageDialogType.TEXT){
            HuDunLanguage auto = DataBaseMgr.getInstance().getLanguageByName("自动检测");
            languages.add(0, auto);
        }

        List<LanguageRecord> records = daoSession.getLanguageRecordDao().queryBuilder()
                .orderDesc(LanguageRecordDao.Properties.Id)
                .list();
        for (LanguageRecord record : records) {
            if(record.getLanguage() == null){
                continue;
            }

            if(languages.size() >= 4){
                break;
            }
            if(addLanguages.contains(record.getLanguage().getName())){
                continue;
            }
            if(isOfflineLang){
                if(!OfflineConstant.INSTANCE.getALL_CODES().contains(mapping(record.getLanguage().getTranslateCode()))){
                    //过滤不支持离线翻译的语种
                    continue;
                }
            }

            if(type == LanguageDialogType.VOICE || type == LanguageDialogType.TO_VOICE) {
                if (!record.getLanguage().getAliAppKey().equals("")) {
                    languages.add(record.getLanguage());
                    addLanguages.add(record.getLanguage().getName());
                }
            }else if(type == LanguageDialogType.FILE || type == LanguageDialogType.TO_FILE) {
                if (!record.getLanguage().getFileRecognitionCode().equals("")) {
                    languages.add(record.getLanguage());
                    addLanguages.add(record.getLanguage().getName());
                }
            }else if(type == LanguageDialogType.TO_FILE_FILTRATION){
                if (!record.getLanguage().getName().equals("中文（文言文）")) {
                    languages.add(record.getLanguage());
                    addLanguages.add(record.getLanguage().getName());
                }
            }else if(type == LanguageDialogType.TEXT || type == LanguageDialogType.TO_TEXT){
                languages.add(record.getLanguage());
                addLanguages.add(record.getLanguage().getName());
            }

        }

        return languages;
    }

    /**
     * 删除多余的记录(超过15条)
     */
    public void deleteExtraRecord(boolean isVoice) {

        long count = daoSession.getLanguageRecordDao().queryBuilder().where(LanguageRecordDao.Properties.IsVoice.eq(isVoice)).count();

        if (count > MAX_NUM_LANGUAGE_RECORD) {

            List<Long> ids = new ArrayList<>();
            List<LanguageRecord> records = daoSession.getLanguageRecordDao().queryBuilder()
                    .where(LanguageRecordDao.Properties.IsVoice.eq(isVoice))
                    .orderDesc(LanguageRecordDao.Properties.Id)
                    .limit((int) (count - MAX_NUM_LANGUAGE_RECORD))
                    .offset(MAX_NUM_LANGUAGE_RECORD).list();
            for (LanguageRecord record : records) {
                ids.add(record.getId());
            }

            daoSession.getLanguageRecordDao().queryBuilder().
                    where(LanguageRecordDao.Properties.Id.in(ids))
                    .buildDelete().executeDeleteWithoutDetachingEntities();
        }
    }

    public void deleteExtraRecord() {
        long count = daoSession.getLanguageRecordDao().queryBuilder().count();
        if (count > MAX_NUM_LANGUAGE_RECORD) {
            List<Long> ids = new ArrayList<>();
            List<LanguageRecord> records = daoSession.getLanguageRecordDao().queryBuilder()
                    .orderDesc(LanguageRecordDao.Properties.Id)
                    .limit((int) (count - MAX_NUM_LANGUAGE_RECORD))
                    .offset(MAX_NUM_LANGUAGE_RECORD).list();
            for (LanguageRecord record : records) {
                ids.add(record.getId());
            }

            daoSession.getLanguageRecordDao().queryBuilder().
                    where(LanguageRecordDao.Properties.Id.in(ids))
                    .buildDelete().executeDeleteWithoutDetachingEntities();
        }
    }

    /**
     * 获取所有记录(是否语音)
     */
    public List<TranslateRecord> getAllRecords(boolean isVoice) {
        if (isVoice) {
            return daoSession.getTranslateRecordDao().queryBuilder().where(TranslateRecordDao.Properties.IsVoice.eq(true))
                    .orderAsc(TranslateRecordDao.Properties.Id).list();
        } else {
            return daoSession.getTranslateRecordDao().queryBuilder().where(TranslateRecordDao.Properties.IsVoice.eq(false))
                    .orderDesc(TranslateRecordDao.Properties.Id).list();
        }

    }

    /**
     * 获取所有记录：语言翻译记录+文本翻译记录
     */
    public List<TranslateRecord> getAllRecords() {
        return daoSession.getTranslateRecordDao().queryBuilder()
                .orderAsc(TranslateRecordDao.Properties.Id).list();
    }

    /**
     * 通过id获取记录(是否语音)
     */
    public TranslateRecord getRecordById(long recordId, boolean isVoice) {
        return daoSession.getTranslateRecordDao().queryBuilder()
                .where(TranslateRecordDao.Properties.IsVoice.eq(isVoice))
                .where(TranslateRecordDao.Properties.Id.eq(recordId))
                .unique();
    }

    public TranslateRecord getRecordById(long recordId) {
        return daoSession.getTranslateRecordDao().queryBuilder()
                .where(TranslateRecordDao.Properties.Id.eq(recordId))
                .unique();
    }

    public List<TranslateRecord> getAllRecords(boolean isVoice,boolean isNation) {
        return daoSession.getTranslateRecordDao().queryBuilder()
                .where(TranslateRecordDao.Properties.IsVoice.eq(isVoice))
                .where(TranslateRecordDao.Properties.IsNation.eq(isNation))
                .orderDesc(TranslateRecordDao.Properties.Id).list();
    }


    /**
     * 获取收藏内容
     */
    public List<TranslateRecord> getCollectedRecords() {
        return daoSession.getTranslateRecordDao().queryBuilder()
                .where(TranslateRecordDao.Properties.IsCollected.eq(true))
                .orderDesc(TranslateRecordDao.Properties.Id).list();
    }

    /**
     * 获取所有语言(分组)
     */
    public List<LanguageGroup> getLanguageGroups(boolean isVoice) {
        List<LanguageGroup> groupList = new ArrayList<>();
        List<HuDunLanguage> allLanguages;
        if (isVoice) {
            allLanguages = daoSession.getHuDunLanguageDao().queryBuilder()
                    .where(HuDunLanguageDao.Properties.SupportVoice.eq(1))
                    .orderAsc(HuDunLanguageDao.Properties.FirstLetter).list();
        } else {
            allLanguages = daoSession.getHuDunLanguageDao().queryBuilder()
                    .orderAsc(HuDunLanguageDao.Properties.FirstLetter).list();
        }


        for (HuDunLanguage language : allLanguages) {

            LanguageGroup group = new LanguageGroup(language.getFirstLetter());
            int index = groupList.indexOf(group);
            if (index == -1) {
                groupList.add(group);
                group.addItem(language);
            } else {
                groupList.get(index).addItem(language);
            }

        }
        return groupList;
    }


    /**
     * 获取所有语言(分组) 排除掉已存在的目标语言，避免选择重复
     */
    public List<LanguageGroup> getLanguageGroups(boolean isNation, boolean isVoice, HuDunLanguage currentLanguage) {
        return getLanguageGroups(isNation, isVoice, currentLanguage, null);
    }

    /**
     * 获取所有文本翻译语种
     */
    public List<HuDunLanguage> getLanguagesForText() {
        return daoSession.getHuDunLanguageDao().queryBuilder()
                .where(HuDunLanguageDao.Properties.TranslateCode.notEq(""))
                .orderAsc(HuDunLanguageDao.Properties.FirstLetter).list();
    }

    /**
     * 获取所有语音翻译语种
     */
    public List<HuDunLanguage> getLanguagesForVoice() {
        return daoSession.getHuDunLanguageDao().queryBuilder()
                .where(HuDunLanguageDao.Properties.AliAppKey.notEq(""))
                .orderAsc(HuDunLanguageDao.Properties.FirstLetter).list();
    }

    /**
     * 获取所有图片翻译语种：支持识别+翻译
     */
    public List<HuDunLanguage> getLanguagesForFile() {
        return daoSession.getHuDunLanguageDao().queryBuilder()
                .where(HuDunLanguageDao.Properties.TranslateCode.notEq(""))
                .where(HuDunLanguageDao.Properties.FileRecognitionCode.notEq(""))
                .orderAsc(HuDunLanguageDao.Properties.FirstLetter).list();
    }

    /**
     * 获取所有取词识别语种
     */
    public List<HuDunLanguage> getLanguagesForWord() {
        return daoSession.getHuDunLanguageDao().queryBuilder()
                .where(HuDunLanguageDao.Properties.SupportDiscern.eq(1))
                .orderAsc(HuDunLanguageDao.Properties.FirstLetter).list();
    }

    public List<LanguageGroup> getLanguageGroups(LanguageDialogType type, boolean isFrom, boolean isOfflineLang) {
        List<LanguageGroup> groupList = new ArrayList<>();
        List<HuDunLanguage> allLanguages;
        ArrayList<String> filtrationLanguages = new ArrayList<>();//过滤语言列表
        filtrationLanguages.add("自动检测");
        //filtrationLanguages.add("夏威夷语");//1.1.7版本暂时不支持夏威夷语
        if(type == LanguageDialogType.VOICE
                || type == LanguageDialogType.TO_VOICE) {
            allLanguages = getLanguagesForVoice();
        }else if(type == LanguageDialogType.FILE
                || type == LanguageDialogType.TO_FILE) {
            allLanguages = getLanguagesForFile();
        }else if(type == LanguageDialogType.TO_FILE_FILTRATION) {
            allLanguages = getLanguagesForText();
            filtrationLanguages.add("中文（文言文）");
        }else if(type == LanguageDialogType.WORD
                || type == LanguageDialogType.TO_WORD) {
            allLanguages = isFrom? getLanguagesForWord() : getLanguagesForText();
        }else{
            allLanguages = getLanguagesForText();
        }

        first:for (HuDunLanguage language : allLanguages) {
            if(isOfflineLang){
                if(!OfflineConstant.INSTANCE.getALL_CODES().contains(mapping(language.getTranslateCode()))){
                    //过滤不支持离线翻译的语种
                    continue;
                }
            }
            second:for(String filtration : filtrationLanguages) {
                if (language.getName().equals(filtration)) {
                    continue first;
                }
            }

            LanguageGroup group = new LanguageGroup(language.getFirstLetter());
            int index = groupList.indexOf(group);
            if (index == -1) {
                groupList.add(group);
                group.addItem(language);
            } else {
                groupList.get(index).addItem(language);
            }
        }

        return groupList;
    }


    /**
     * 获取所有语言(分组) 排除掉已存在的目标语言，避免选择重复
     */
    public List<LanguageGroup> getLanguageGroups(boolean isNation, boolean isVoice, HuDunLanguage currentLanguage, List<String> filterLangList) {
        List<LanguageGroup> groupList = new ArrayList<>();
        List<HuDunLanguage> allLanguages;
        if (isVoice) {
            allLanguages = daoSession.getHuDunLanguageDao().queryBuilder()
                    .where(HuDunLanguageDao.Properties.SupportVoice.eq(1))
                    .orderAsc(HuDunLanguageDao.Properties.FirstLetter).list();
        } else {
            allLanguages = daoSession.getHuDunLanguageDao().queryBuilder()
                    .orderAsc(HuDunLanguageDao.Properties.FirstLetter).list();
        }

        for (HuDunLanguage language : allLanguages) {
            if (null != currentLanguage) {
                if (language.getName().equals(currentLanguage.getName())) {
                    continue;
                }
            }
            if (language.getName().equals("自动检测")) {
                continue;
            }
            if(isNation){
                if (!language.getName().equals("中文（简体）")
                        && !language.getName().equals("维吾尔语")
                        && !language.getName().equals("藏语")
                        && !language.getName().equals("蒙古语")
                ) {
                    continue;
                }
            }

            //过滤掉不支持的语种
            if(filterLangList != null && filterLangList.size() > 0){
                if(filterLangList.contains(language.getName())){
                    continue;
                }
            }

            LanguageGroup group = null;
            if(isNation){
                group = new LanguageGroup(AppContextProvider.getContext().getResources().getString(R.string.text_mzyy));
            }else {
                group = new LanguageGroup(language.getFirstLetter());
            }
            int index = groupList.indexOf(group);
            if (index == -1) {
                groupList.add(group);
                group.addItem(language);
            } else {
                groupList.get(index).addItem(language);
            }

        }
        return groupList;
    }

    /**
     * 获取民族语言
     */
    public List<LanguageGroup> getNationLanguageGroups(boolean isVoice, HuDunLanguage currentLanguage) {
        List<LanguageGroup> groupList = new ArrayList<>();
        List<HuDunLanguage> allLanguages;
        if (isVoice) {
            allLanguages = daoSession.getHuDunLanguageDao().queryBuilder()
                    .where(HuDunLanguageDao.Properties.SupportVoice.eq(1))
                    .orderAsc(HuDunLanguageDao.Properties.FirstLetter).list();
        } else {
            allLanguages = daoSession.getHuDunLanguageDao().queryBuilder()
                    .orderAsc(HuDunLanguageDao.Properties.FirstLetter).list();
        }

        for (HuDunLanguage language : allLanguages) {
            if (null != currentLanguage) {
                if (language.getName().equals(currentLanguage.getName())) {
                    continue;
                }
                if (!language.getName().equals("中文（简体）")
                        || !language.getName().equals("维吾尔语")
                        || !language.getName().equals("藏语")
                        || !language.getName().equals("蒙古语")
                ) {
                    continue;
                }
            }
            LanguageGroup group = new LanguageGroup(language.getFirstLetter());
            int index = groupList.indexOf(group);
            if (index == -1) {
                groupList.add(group);
                group.addItem(language);
            } else {
                groupList.get(index).addItem(language);
            }

        }
        return groupList;
    }


    /**
     * 如果原数据库有原文与翻译一样的数据，清除掉原来的数据。
     */
    public boolean isContain(TranslateRecord record) {
        if (record == null) return false;
        List<TranslateRecord> list = daoSession.getTranslateRecordDao().queryBuilder().where(TranslateRecordDao.Properties.IsVoice.eq(false))
                .orderDesc(TranslateRecordDao.Properties.Id).list();

        for (TranslateRecord translateRecord : list) {
            if (translateRecord.getContentOrig().equals(record.getContentOrig()) &&
                    translateRecord.getContentTranslate().equals(record.getContentTranslate())) {
                deleteRecord(translateRecord);
                return true;
            }
        }
        return false;
    }


    /**
     * 获取所有限制规则表
     */
    public List<Limit4UseBean> getLimitAll() {
        return daoSession.getLimit4UseBeanDao().loadAll();
    }

    public Limit4UseBean getLimit2Code(EventCode eventCode) {
        return daoSession.getLimit4UseBeanDao().queryBuilder().where(Limit4UseBeanDao.Properties.M_code.eq(eventCode.getCode())).unique();
    }

    /**
     * 更新记录
     */
    public void updateLimit(Limit4UseBean limit) {
        if (limit == null)
            return;
        daoSession.getLimit4UseBeanDao().update(limit);
    }

    /**
     * 减少使用次数
     */
    public void subLimitCount(Limit4UseBean limit) {
        limit.setCount(limit.getCount() - 1);
        updateLimit(limit);
    }

    /**
     * 减少使用时长
     */
    public void subLimitTime(Limit4UseBean limit, long useTime) {
        Long time = limit.getTime();
        limit.setTime( time- useTime);
        Log.i("subLimitTime","limitTIme = "+(time- useTime));
        updateLimit(limit);
    }

    public void addLimit(Limit4UseBean limit) {
        if (limit == null)
            return;
        daoSession.getLimit4UseBeanDao().insertOrReplace(limit);
    }

    public List<LanguageGroup> getLanguageGroups(HuDunLanguage currentLanguage) {

        List<LanguageGroup> groupList = new ArrayList<>();
        List<HuDunLanguage> allLanguages;
        allLanguages = daoSession.getHuDunLanguageDao().queryBuilder()
                .where(HuDunLanguageDao.Properties.SupportVoice.eq(1))
                .orderAsc(HuDunLanguageDao.Properties.FirstLetter).list();

        for (HuDunLanguage language : allLanguages) {
            if (null != currentLanguage) {
                if (language.getName().equals(currentLanguage.getName())) {
                    continue;
                }
            }
            if (!language.getName().equals("中文（简体）")
                    && !language.getName().equals("英语")
                    && !language.getName().equals("日语")
                    && !language.getName().equals("韩语")
                    && !language.getName().equals("德语")
                    && !language.getName().equals("法语")
                    && !language.getName().equals("西班牙语")
            ) {
                continue;
            }
            LanguageGroup group = new LanguageGroup(AppContextProvider.getContext().getResources().getString(R.string.text_cgjjb));
            int index = groupList.indexOf(group);
            if (index == -1) {
                groupList.add(group);
                group.addItem(language);
            } else {
                groupList.get(index).addItem(language);
            }

        }
        return groupList;
    }
}
